<?php defined('SYSPATH') or die('No direct script access.');
	/**
	 * create connect with RedisDB
	 *
	 * @return  void
	 */
class Kohana_RedisDB {

	public static $instances = array();

	public static $default = 'default';

                                    //$connect = NULL, $port = NULL, $timeout = NULL
	public static function instance($type = NULL)
	{
		if ( ! isset(RedisDB::$instances[$type]))
		{
			$type = RedisDB::$default;

			if ( ! isset(RedisDB::$instances[$type]))
			{
				// Load the configuration for this type
				$config = Kohana::$config->load('redisdb')->get($type);

				new RedisDB($config,$type);
			}
		}

		return RedisDB::$instances[$type];
	}


	protected $_connect = '127.0.0.1';

	protected $_port = NULL;

	protected $_timeout = 0;

	protected $_database = 1;

	public function __construct(array $config = NULL,$type)
	{
		if (isset($config['connect']))
		{
			$this->_connect = (string) $config['connect'];
		}

		if (isset($config['port']))
		{
			$this->_port = (int) $config['port'];
		}

		if (isset($config['timeout']))
		{
			$this->_timeout = (int) $config['timeout'];
		}

		if (isset($config['database']))
		{
			$this->_database = (int) $config['database'];
		}

		$this->conn($type);
	}

	/**
	 * create a new instance with RedisDB
	 *
	 * @return  void
	 */
	private function conn($type)
	{
		// Create a new instance
		try
		{
			RedisDB::$instances[$type] =  new Redis();
		}
		catch (Exception $e)
		{
			// Log & ignore all errors when a write fails
			Kohana::$log->add(Log::ERROR, Kohana_Exception::text($e))->write();

			return FALSE;
		}

		if ($this->_connect !== NULL AND $this->_port !== NULL AND $this->_timeout > 0)
		{
			try
			{
				RedisDB::$instances[$type]->connect($this->_connect,$this->_port,$this->_timeout);
			}
			catch (Exception $e)
			{
				// Log & ignore all errors when a write fails
				Kohana::$log->add(Log::ERROR, Kohana_Exception::text($e))->write();

				return FALSE;
			}
		}
		elseif ($this->_connect !== NULL AND $this->_port !== NULL)
		{
			try
			{
				RedisDB::$instances[$type]->connect($this->_connect,$this->_port);
			}
			catch (Exception $e)
			{
				// Log & ignore all errors when a write fails
				Kohana::$log->add(Log::ERROR, Kohana_Exception::text($e))->write();

				return FALSE;
			}
		}
		else
		{
			try
			{
				RedisDB::$instances[$type]->connect($this->_connect);
			}
			catch (Exception $e)
			{
				// Log & ignore all errors when a write fails
				Kohana::$log->add(Log::ERROR, Kohana_Exception::text($e))->write();

				return FALSE;
			}
		}
        if ($this->_database > 1)
        {
        	RedisDB::$instances[$type]->select($this->_database);
        }
		//RedisDB::$instances[$type]->incr('global:page_requests');

	}

}